﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Text;

namespace Public
{
    public class SendEmail
    {
        static string strHost = String.Empty;
        static string strAccount = String.Empty;
        static string strPwd = String.Empty;
        static string strFrom = String.Empty;
        private static string strPort = String.Empty;
         /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="to">接收方邮件地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件正文内容</param>
        public static bool Sendmail(DataTable dt,string to, string title, string content)
         {
             bool flag = false;
             if (dt.Rows.Count > 0)
             {
                 strHost = dt.Rows[0]["MailSmtp"].ToString(); //STMP服务器地址
                 strAccount = dt.Rows[0]["MailAccount"].ToString(); //SMTP服务帐号
                 strPwd = dt.Rows[0]["MailPassword"].ToString(); //SMTP服务密码
                 strFrom = dt.Rows[0]["MailFrom"].ToString(); //发送方邮件地址
                 strPort = dt.Rows[0]["MailPort"].ToString();

                 SmtpClient _smtpClient = new SmtpClient();
                 _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; //指定电子邮件发送方式
                 _smtpClient.Host = strHost;
                 _smtpClient.Port = Convert.ToInt32(strPort);
                 ; //指定SMTP服务器
                 _smtpClient.Credentials = new System.Net.NetworkCredential(strAccount, strPwd); //用户名和密码

                 MailMessage _mailMessage = new MailMessage(strFrom, to);
                 _mailMessage.Subject = title; //主题
                 _mailMessage.Body = content; //内容
                 _mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding(dt.Rows[0]["MailCharset"].ToString());//正文编码
                 _mailMessage.IsBodyHtml = true; //设置为HTML格式
                 _mailMessage.Priority = MailPriority.High; //优先级

                 try
                 {
                     _smtpClient.Send(_mailMessage);
                     flag= true;
                 }
                 catch
                 {
                     flag= false;
                 }
             }
             return flag;
         }
    }
}
